// 高级Model-Viewer控制器
class AdvancedModelViewerController {
    constructor(modelViewerElement) {
        this.modelViewer = modelViewerElement;
        this.isLoaded = false;
        this.currentView = 'exterior';
        this.autoRotateSpeed = 5;
        this.presets = {
            'exterior': { orbit: '0deg 75deg 75%', fov: '30deg' },
            'interior': { orbit: '0deg 45deg 50%', fov: '45deg' },
            'front': { orbit: '0deg 75deg 75%', fov: '30deg' },
            'back': { orbit: '180deg 75deg 75%', fov: '30deg' },
            'left': { orbit: '90deg 75deg 75%', fov: '30deg' },
            'right': { orbit: '-90deg 75deg 75%', fov: '30deg' },
            'top': { orbit: '0deg 0deg 75%', fov: '30deg' },
            'close': { orbit: '0deg 75deg 50%', fov: '45deg' },
            'far': { orbit: '0deg 75deg 100%', fov: '25deg' }
        };
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.createAdvancedControls();
        this.bindKeyboardShortcuts();
        this.bindTouchGestures();
    }
    
    bindEvents() {
        this.modelViewer.addEventListener('load', () => this.onModelLoad());
        this.modelViewer.addEventListener('error', (event) => this.onModelError(event));
        this.modelViewer.addEventListener('camera-change', () => this.onCameraChange());
    }
    
    onModelLoad() {
        console.log('模型加载成功');
        this.isLoaded = true;
        this.hideLoadingOverlay();
        this.setView('exterior');
    }
    
    onModelError(event) {
        console.error('模型加载失败:', event.detail);
        this.showErrorOverlay();
    }
    
    onCameraChange() {
        // 可以在这里添加相机变化时的逻辑
        console.log('相机视角已改变');
    }
    
    createAdvancedControls() {
        // 创建高级控制面板
        const controlsContainer = document.createElement('div');
        controlsContainer.className = 'advanced-controls';
        controlsContainer.innerHTML = `
            <div class="control-section">
                <h3>视角预设</h3>
                <div class="preset-buttons">
                    <button data-preset="exterior">外部</button>
                    <button data-preset="interior">内部</button>
                    <button data-preset="front">正面</button>
                    <button data-preset="back">背面</button>
                    <button data-preset="left">左侧</button>
                    <button data-preset="right">右侧</button>
                    <button data-preset="top">顶部</button>
                </div>
            </div>
            <div class="control-section">
                <h3>渲染设置</h3>
                <div class="slider-control">
                    <label>旋转速度: <span id="rotationValue">5</span></label>
                    <input type="range" id="rotationSpeed" min="0" max="10" value="5" step="0.1">
                </div>
                <div class="slider-control">
                    <label>曝光度: <span id="exposureValue">1.0</span></label>
                    <input type="range" id="exposure" min="0" max="2" value="1" step="0.1">
                </div>
                <div class="slider-control">
                    <label>阴影强度: <span id="shadowValue">1.0</span></label>
                    <input type="range" id="shadowIntensity" min="0" max="2" value="1" step="0.1">
                </div>
            </div>
            <div class="control-section">
                <h3>环境设置</h3>
                <div class="environment-controls">
                    <button data-env="neutral">中性</button>
                    <button data-env="sunset">日落</button>
                    <button data-env="dawn">黎明</button>
                    <button data-env="night">夜晚</button>
                    <button data-env="warehouse">仓库</button>
                    <button data-env="forest">森林</button>
                </div>
            </div>
        `;
        
        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .advanced-controls {
                position: absolute;
                top: 20px;
                right: 20px;
                z-index: 1000;
                background: rgba(0,21,41,0.9);
                border: 1px solid var(--panel-border-color);
                border-radius: 8px;
                padding: 20px;
                backdrop-filter: blur(10px);
                max-width: 300px;
                max-height: 80vh;
                overflow-y: auto;
            }
            .control-section {
                margin-bottom: 20px;
            }
            .control-section h3 {
                color: var(--primary-color);
                margin-bottom: 10px;
                font-size: 14px;
            }
            .preset-buttons, .environment-controls {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 8px;
            }
            .preset-buttons button, .environment-controls button {
                background: transparent;
                border: 1px solid var(--panel-border-color);
                color: #fff;
                padding: 6px 12px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 12px;
                transition: all 0.3s ease;
            }
            .preset-buttons button:hover, .environment-controls button:hover {
                background: var(--primary-color);
                border-color: var(--primary-color);
            }
            .preset-buttons button.active, .environment-controls button.active {
                background: var(--primary-color);
                border-color: var(--primary-color);
            }
            .slider-control {
                margin-bottom: 15px;
            }
            .slider-control label {
                display: block;
                font-size: 12px;
                color: #ccc;
                margin-bottom: 5px;
            }
            .slider-control input[type="range"] {
                width: 100%;
                background: transparent;
            }
            .slider-control input[type="range"]::-webkit-slider-thumb {
                background: var(--primary-color);
            }
            .slider-control input[type="range"]::-moz-range-thumb {
                background: var(--primary-color);
            }
        `;
        
        document.head.appendChild(style);
        document.body.appendChild(controlsContainer);
        
        // 绑定控制事件
        this.bindControlEvents(controlsContainer);
    }
    
    bindControlEvents(container) {
        // 预设视角按钮
        container.querySelectorAll('[data-preset]').forEach(button => {
            button.addEventListener('click', () => {
                const preset = button.dataset.preset;
                this.setView(preset);
                
                // 更新按钮状态
                container.querySelectorAll('[data-preset]').forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
            });
        });
        
        // 环境设置按钮
        container.querySelectorAll('[data-env]').forEach(button => {
            button.addEventListener('click', () => {
                const env = button.dataset.env;
                this.setEnvironment(env);
                
                // 更新按钮状态
                container.querySelectorAll('[data-env]').forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
            });
        });
        
        // 滑块控制
        const rotationSpeed = container.querySelector('#rotationSpeed');
        const exposure = container.querySelector('#exposure');
        const shadowIntensity = container.querySelector('#shadowIntensity');
        
        if (rotationSpeed) {
            rotationSpeed.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.setRotationSpeed(value);
                container.querySelector('#rotationValue').textContent = value;
            });
        }
        
        if (exposure) {
            exposure.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.setExposure(value);
                container.querySelector('#exposureValue').textContent = value.toFixed(1);
            });
        }
        
        if (shadowIntensity) {
            shadowIntensity.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                this.setShadowIntensity(value);
                container.querySelector('#shadowValue').textContent = value.toFixed(1);
            });
        }
    }
    
    setView(viewType) {
        this.currentView = viewType;
        
        if (this.presets[viewType]) {
            const preset = this.presets[viewType];
            this.modelViewer.cameraOrbit = preset.orbit;
            this.modelViewer.fieldOfView = preset.fov;
        }
    }
    
    setEnvironment(envType) {
        this.modelViewer.environmentImage = envType;
    }
    
    setRotationSpeed(speed) {
        this.autoRotateSpeed = speed;
        if (speed > 0) {
            this.modelViewer.autoRotate = true;
            this.modelViewer.autoRotateDelay = 0;
            this.modelViewer.autoRotateSpeed = speed;
        } else {
            this.modelViewer.autoRotate = false;
        }
    }
    
    setExposure(exposure) {
        this.modelViewer.exposure = exposure;
    }
    
    setShadowIntensity(intensity) {
        this.modelViewer.shadowIntensity = intensity;
    }
    
    hideLoadingOverlay() {
        const loadingOverlay = document.getElementById('loadingOverlay');
        if (loadingOverlay) {
            loadingOverlay.style.opacity = '0';
            setTimeout(() => {
                loadingOverlay.style.display = 'none';
            }, 500);
        }
    }
    
    showErrorOverlay() {
        const loadingOverlay = document.getElementById('loadingOverlay');
        if (loadingOverlay) {
            loadingOverlay.innerHTML = `
                <div style="text-align: center; color: #f5222d;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; margin-bottom: 20px;"></i>
                    <div>模型加载失败</div>
                    <div style="font-size: 12px; margin-top: 10px;">请检查Model.glb文件是否存在</div>
                </div>
            `;
        }
    }
    
    bindKeyboardShortcuts() {
        document.addEventListener('keydown', (event) => {
            switch(event.key) {
                case '1':
                    this.setView('exterior');
                    break;
                case '2':
                    this.setView('interior');
                    break;
                case '3':
                    this.setView('front');
                    break;
                case '4':
                    this.setView('back');
                    break;
                case '5':
                    this.setView('left');
                    break;
                case '6':
                    this.setView('right');
                    break;
                case '7':
                    this.setView('top');
                    break;
                case 'r':
                case 'R':
                    this.resetView();
                    break;
                case 'f':
                case 'F':
                    this.toggleFullscreen();
                    break;
                case ' ':
                    event.preventDefault();
                    this.modelViewer.autoRotate = !this.modelViewer.autoRotate;
                    break;
                case 'ArrowUp':
                    event.preventDefault();
                    this.adjustCamera('up');
                    break;
                case 'ArrowDown':
                    event.preventDefault();
                    this.adjustCamera('down');
                    break;
                case 'ArrowLeft':
                    event.preventDefault();
                    this.adjustCamera('left');
                    break;
                case 'ArrowRight':
                    event.preventDefault();
                    this.adjustCamera('right');
                    break;
            }
        });
    }
    
    bindTouchGestures() {
        let touchStartX = 0;
        let touchStartY = 0;
        let touchStartTime = 0;
        let touchCount = 0;
        
        this.modelViewer.addEventListener('touchstart', (event) => {
            touchStartX = event.touches[0].clientX;
            touchStartY = event.touches[0].clientY;
            touchStartTime = Date.now();
            touchCount++;
        });
        
        this.modelViewer.addEventListener('touchend', (event) => {
            const touchEndX = event.changedTouches[0].clientX;
            const touchEndY = event.changedTouches[0].clientY;
            const touchEndTime = Date.now();
            const deltaX = touchEndX - touchStartX;
            const deltaY = touchEndY - touchStartY;
            const deltaTime = touchEndTime - touchStartTime;
            
            // 双击重置视角
            if (Math.abs(deltaX) < 10 && Math.abs(deltaY) < 10 && deltaTime < 300) {
                this.resetView();
            }
            
            // 三击切换全屏
            if (touchCount >= 3) {
                this.toggleFullscreen();
                touchCount = 0;
            }
        });
    }
    
    resetView() {
        this.setView('exterior');
    }
    
    toggleFullscreen() {
        if (this.modelViewer.requestFullscreen) {
            this.modelViewer.requestFullscreen();
        } else if (this.modelViewer.webkitRequestFullscreen) {
            this.modelViewer.webkitRequestFullscreen();
        } else if (this.modelViewer.msRequestFullscreen) {
            this.modelViewer.msRequestFullscreen();
        }
    }
    
    adjustCamera(direction) {
        const currentOrbit = this.modelViewer.cameraOrbit;
        const [theta, phi, radius] = currentOrbit.split(' ').map(Number);
        
        switch (direction) {
            case 'up':
                this.modelViewer.cameraOrbit = `${theta}deg ${Math.max(0, phi - 10)}deg ${radius}%`;
                break;
            case 'down':
                this.modelViewer.cameraOrbit = `${theta}deg ${Math.min(180, phi + 10)}deg ${radius}%`;
                break;
            case 'left':
                this.modelViewer.cameraOrbit = `${theta - 10}deg ${phi}deg ${radius}%`;
                break;
            case 'right':
                this.modelViewer.cameraOrbit = `${theta + 10}deg ${phi}deg ${radius}%`;
                break;
        }
    }
    
    // 动画到指定视角
    animateToView(targetOrbit, duration = 2000) {
        const startOrbit = this.modelViewer.cameraOrbit;
        const startTime = Date.now();
        
        const animate = () => {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            // 缓动函数
            const easeInOutCubic = t => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
            const easedProgress = easeInOutCubic(progress);
            
            const [startTheta, startPhi, startRadius] = startOrbit.split(' ').map(Number);
            const [targetTheta, targetPhi, targetRadius] = targetOrbit.split(' ').map(Number);
            
            const currentTheta = startTheta + (targetTheta - startTheta) * easedProgress;
            const currentPhi = startPhi + (targetPhi - startPhi) * easedProgress;
            const currentRadius = startRadius + (targetRadius - startRadius) * easedProgress;
            
            this.modelViewer.cameraOrbit = `${currentTheta}deg ${currentPhi}deg ${currentRadius}%`;
            
            if (progress < 1) {
                requestAnimationFrame(animate);
            }
        };
        
        animate();
    }
    
    // 截图功能
    captureScreenshot() {
        return new Promise((resolve) => {
            this.modelViewer.addEventListener('screenshot', (event) => {
                resolve(event.detail);
            }, { once: true });
            this.modelViewer.screenshot();
        });
    }
    
    // 获取模型信息
    getModelInfo() {
        return {
            isLoaded: this.isLoaded,
            currentView: this.currentView,
            autoRotate: this.modelViewer.autoRotate,
            autoRotateSpeed: this.autoRotateSpeed,
            cameraOrbit: this.modelViewer.cameraOrbit,
            fieldOfView: this.modelViewer.fieldOfView,
            exposure: this.modelViewer.exposure,
            shadowIntensity: this.modelViewer.shadowIntensity
        };
    }
}

// 导出控制器类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AdvancedModelViewerController;
} 